﻿/***************************************************************************
* Copyright(C)   2013  Granger Corporation
* All rights reserved
*
* Author: Granger(Granger@haipos.com)
* CreateDate: 2013/7/5 12:37:10
* Description:
*
* Revision History
* Date					Author		Versions		Description
* 2013/7/5 12:37:10	Granger		v1.0
**************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;
namespace UNSite.Starter
{
    /// <summary>
    /// 模块装配
    /// </summary>
    public static class HostContainer
    {
        private static IContainer container=null;

        public static IContainer Container
        {
            get { return container; }
            set { container = value; }
        }

       static object lockObj = 1; //锁对象，保证单次注入

        /// <summary>
        /// AutoFac注入
        /// </summary>
        public static void Register()
        {
            lock (lockObj)//进程锁
            {
                if (container == null)
                {
                    //IOC注入
                    ContainerBuilder Builder = new ContainerBuilder();

                    //单例注册
                  //  Builder.RegisterInstance(new UNSite.Core.Cache.WebCache()).As<UNSite.Core.Cache.IDataCache>();

                    //Builder.RegisterType<UNSite.Core.Data.SqlServer.MsSqlHelper>().As<UNSite.Core.Data.ISqlHelper>();
                    //Builder.RegisterType<UNSite.Core.Data.SqlServer.MsSqlBuilder>().As<UNSite.Core.Data.ISqlBuilder>();

                    //Builder.RegisterInstance(new UNSite.Core.Data.SqlServer.MsSqlBuilder()).As<UNSite.Core.Data.ISqlBuilder>();
                    //Builder.RegisterInstance(new UNSite.Core.Data.SqlServer.MsSqlHelper()).As<UNSite.Core.Data.ISqlHelper>();

                    //注册所UNSite.BLL下所有对象，并设置循环依赖
                     Builder.RegisterAssemblyTypes(typeof(ModelLib.Test).Assembly).PropertiesAutowired();
                 //  Builder.RegisterType<ModelLib.Test>();
                    container = Builder.Build();
                }
            }
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve<T>() where T:class,new()
        {
            if (container.IsRegistered(typeof(T)))
            {
                return container.Resolve<T>();
            }
            else
            {
                return null;
            }
        }


    }//class
}//namespace
